package org.mx.dal.test.config;

import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

import javax.sql.DataSource;

import org.mx.error.UserInterfaceSystemErrorException;
import org.mx.error.UserInterfaceSystemErrorException.SystemErrors;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.transaction.annotation.EnableTransactionManagement;

import com.alibaba.druid.pool.DruidDataSourceFactory;
import com.alibaba.druid.pool.xa.DruidXADataSource;
import com.atomikos.jdbc.AtomikosDataSourceBean;

@SuppressWarnings("javadoc")
@Configuration
@EnableTransactionManagement
public class DataSourceConfig {
	@ConfigurationProperties(prefix = "spring.datasource.one")
	@Qualifier("dsOneMap")
	public Map<String, Object> dsOneMap() {
		return new HashMap<>();
	}

	@ConfigurationProperties(prefix = "spring.datasource.two")
	@Qualifier("dsOneMap")
	public Map<String, Object> dsTwoMap() {
		return new HashMap<>();
	}

	private DataSource createXaDataSource(String name, Map<String, Object> dsMap) {
		DruidXADataSource druidXa = new DruidXADataSource();
		try {
			DruidDataSourceFactory.config(druidXa, dsMap);
		} catch (SQLException e) {
			throw new UserInterfaceSystemErrorException(SystemErrors.SYSTEM_ILLEGAL_PARAM);
		}
		AtomikosDataSourceBean xaDs = new AtomikosDataSourceBean();
		xaDs.setUniqueResourceName(name);
		xaDs.setXaDataSource(druidXa);
		return xaDs;
	}

	@Bean(name = "dsOne")
	public DataSource dsOne(@Qualifier("dsOneMap") Map<String, Object> dsOneMap) {
		return createXaDataSource("dsOne", dsOneMap);
	}

	@Bean(name = "dsTwo")
	public DataSource dsTwo(@Qualifier("dsOneMap") Map<String, Object> dsOneMap) {
		return createXaDataSource("dsTwo", dsOneMap);
	}
}
